<!--
  系统集成功能演示页面
  
  展示Electron中各种系统集成功能：
  - 系统托盘
  - 全局快捷键
  - 应用菜单
  - 上下文菜单
  - 系统通知
  - 协议注册
  - 开机自启动
-->

<template>
  <div class="system-integration-page">
    <!-- 页面标题 -->
    <div class="header">
      <h2>🔧 系统集成演示</h2>
      <p class="subtitle">展示 Electron 与操作系统的深度集成功能</p>
      
      <!-- 快速菜单栏控制 -->
      <div class="quick-menu-control">
        <button @click="toggleMenuBar" :class="['btn', 'btn-lg', menuStatus.visible ? 'btn-warning' : 'btn-success']">
          {{ menuStatus.visible ? '🔽 隐藏应用菜单栏' : '🔼 显示应用菜单栏' }}
        </button>
        <p class="menu-status-text">当前状态: {{ menuStatus.visible ? '菜单栏已显示' : '菜单栏已隐藏' }}</p>
      </div>
    </div>

    <!-- 功能分组 -->
    <div class="demo-sections">
      
      <!-- 1. 系统托盘 -->
      <div class="demo-section">
        <h3>🗂️ 系统托盘</h3>
        <p class="description">在系统托盘中显示应用图标，提供快捷访问菜单</p>
        <div class="controls">
          <button @click="createTray" class="btn btn-primary" :disabled="trayStatus.created">
            {{ trayStatus.created ? '✓ 托盘已创建' : '创建系统托盘' }}
          </button>
          <button @click="destroyTray" class="btn btn-secondary" :disabled="!trayStatus.created">
            销毁托盘
          </button>
          <button @click="updateTrayMenu" class="btn btn-success" :disabled="!trayStatus.created">
            更新托盘菜单
          </button>
        </div>
        <div v-if="trayStatus.created" class="status-info">
          <p>✅ 系统托盘已激活 - 点击托盘图标查看菜单</p>
          <p>🖱️ 单击切换窗口显示，双击恢复窗口</p>
        </div>
      </div>

      <!-- 2. 全局快捷键 -->
      <div class="demo-section">
        <h3>⌨️ 全局快捷键</h3>
        <p class="description">注册系统级快捷键，即使应用不在前台也能响应</p>
        <div class="controls">
          <div class="shortcut-item">
            <input 
              v-model="newShortcut" 
              placeholder="输入快捷键组合，如: Ctrl+Shift+A"
              class="input"
            >
            <select v-model="shortcutAction" class="action-select">
              <option value="show-hide-window">显示/隐藏窗口</option>
              <option value="show-notification">发送通知</option>
              <option value="custom-action">自定义动作</option>
            </select>
            <button @click="registerShortcut" class="btn btn-primary">注册快捷键</button>
          </div>
        </div>
        <div class="shortcut-list">
          <h4>已注册的快捷键：</h4>
          <div v-if="shortcuts.length === 0" class="empty-state">
            暂无注册的快捷键
          </div>
          <div v-else>
            <div v-for="shortcut in shortcuts" :key="shortcut.key" class="shortcut-card">
              <span class="shortcut-key">{{ shortcut.key }}</span>
              <span class="shortcut-desc">{{ shortcut.description }}</span>
              <span class="shortcut-action">{{ shortcut.action }}</span>
              <button @click="unregisterShortcut(shortcut.key)" class="btn btn-danger btn-sm">
                移除
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 3. 系统通知 -->
      <div class="demo-section">
        <h3>🔔 系统通知</h3>
        <p class="description">发送操作系统原生通知，支持各种配置选项</p>
        <div class="controls">
          <div class="notification-form">
            <input 
              v-model="notification.title" 
              placeholder="通知标题"
              class="input"
            >
            <textarea 
              v-model="notification.body" 
              placeholder="通知内容"
              class="textarea"
            ></textarea>
            <div class="notification-options">
              <label class="checkbox-item">
                <input type="checkbox" v-model="notification.silent">
                静默通知（无声音）
              </label>
              <label class="checkbox-item">
                <input type="checkbox" v-model="notification.urgent">
                紧急通知
              </label>
            </div>
            <div class="notification-controls">
              <button @click="sendNotification" class="btn btn-primary">发送通知</button>
              <button @click="testUrgentNotification" class="btn btn-warning">测试紧急通知</button>
              <button @click="playNotificationSound" class="btn btn-info">测试声音</button>
            </div>
          </div>
        </div>
        <div class="notification-history">
          <h4>通知历史：</h4>
          <div v-if="notificationHistory.length === 0" class="empty-state">
            暂无发送记录
          </div>
          <div v-else class="history-list">
            <div v-for="(item, index) in notificationHistory" :key="index" class="history-item">
              <div class="history-time">{{ item.time }}</div>
              <div class="history-content">
                <strong>{{ item.title }}</strong>
                <p>{{ item.body }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 4. 应用菜单 -->
      <div class="demo-section">
        <h3>📋 应用菜单</h3>
        <p class="description">自定义应用菜单栏，添加各种菜单项和快捷键</p>
        <div class="controls">
          <button @click="setCustomMenu" class="btn btn-primary">设置自定义菜单</button>
          <button @click="resetDefaultMenu" class="btn btn-secondary">恢复默认菜单</button>
          <button @click="toggleMenuBar" :class="['btn', menuStatus.visible ? 'btn-warning' : 'btn-success']">
            {{ menuStatus.visible ? '🔽 隐藏菜单栏' : '🔼 显示菜单栏' }}
          </button>
          <button @click="createMenuWindow" class="btn btn-info">🪟 创建带菜单栏的窗口</button>
        </div>
        <div class="menu-info">
          <p>当前菜单状态: {{ menuStatus.isCustom ? '自定义菜单' : '默认菜单' }}</p>
          <p>菜单栏显示: {{ menuStatus.visible ? '显示' : '隐藏' }}</p>
          <div class="menu-notice">
            <p><strong>📋 说明：</strong></p>
            <p>• 当前主窗口为无边框设计，菜单栏可能无法正常显示</p>
            <p>• 点击"创建带菜单栏的窗口"可在新窗口中查看完整菜单栏效果</p>
            <p>• 新窗口将展示包含文件、编辑、查看、帮助等完整菜单</p>
          </div>
        </div>
      </div>

      <!-- 5. 协议注册 -->
      <div class="demo-section">
        <h3>🔗 协议注册</h3>
        <p class="description">注册自定义URL协议，让系统能够通过URL打开应用</p>
        <div class="controls">
          <button @click="registerProtocol" class="btn btn-primary">注册 yucloudele:// 协议</button>
          <button @click="testProtocol" class="btn btn-success">测试协议链接</button>
        </div>
        <div class="protocol-info">
          <p>协议状态: {{ protocolStatus.registered ? '已注册' : '未注册' }}</p>
          <p v-if="protocolStatus.registered">
            测试链接: <code>yucloudele://test?param=hello</code>
          </p>
        </div>
      </div>

      <!-- 6. 开机自启动 -->
      <div class="demo-section">
        <h3>🚀 开机自启动</h3>
        <p class="description">设置应用开机自动启动</p>
        <div class="controls">
          <button @click="toggleAutoLaunch" class="btn btn-primary">
            {{ autoLaunchStatus.enabled ? '禁用' : '启用' }}开机自启动
          </button>
          <button @click="checkAutoLaunch" class="btn btn-secondary">检查启动状态</button>
        </div>
        <div class="autolaunch-info">
          <p>自启动状态: {{ autoLaunchStatus.enabled ? '✅ 已启用' : '❌ 已禁用' }}</p>
          <p v-if="autoLaunchStatus.path">安装路径: {{ autoLaunchStatus.path }}</p>
        </div>
      </div>

    </div>

    <!-- 消息提示 -->
    <div v-if="message.text" :class="['message', message.type]">
      {{ message.text }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useSettings } from '../stores/settings'

const router = useRouter()
const settings = useSettings()

// 托盘状态
const trayStatus = reactive({
  created: false
})

// 快捷键管理
const newShortcut = ref('')
const shortcutAction = ref('show-hide-window')
const shortcuts = ref<Array<{key: string, description: string, action: string}>>([])

// 通知管理
const notification = reactive({
  title: 'yuCloudEle 通知',
  body: '这是一个来自 Electron 应用的系统通知！',
  silent: false,
  urgent: false
})

const notificationHistory = ref<Array<{time: string, title: string, body: string}>>([])

// 菜单状态
const menuStatus = reactive({
  isCustom: false,
  visible: true
})

// 协议状态
const protocolStatus = reactive({
  registered: false
})

// 自启动状态
const autoLaunchStatus = reactive({
  enabled: false,
  path: ''
})

// 消息提示
const message = reactive({
  text: '',
  type: 'info'
})

/**
 * 创建系统托盘
 */
const createTray = async () => {
  try {
    const result = await window.api.system.createTray()
    
    if (result.success) {
      trayStatus.created = true
      showMessage('系统托盘创建成功！', 'success')
    }
  } catch (error) {
    showMessage('创建系统托盘失败: ' + error, 'error')
  }
}

/**
 * 销毁系统托盘
 */
const destroyTray = async () => {
  try {
    await window.api.system.destroyTray()
    trayStatus.created = false
    showMessage('系统托盘已销毁', 'info')
  } catch (error) {
    showMessage('销毁托盘失败: ' + error, 'error')
  }
}

/**
 * 更新托盘菜单
 */
const updateTrayMenu = async () => {
  try {
    await window.api.system.updateTrayMenu([
      { label: '🎉 更新后的菜单', action: 'show' },
      { label: '📱 新功能', action: 'newfeature' },
      { type: 'separator' },
      { label: '退出', action: 'quit' }
    ])
    showMessage('托盘菜单已更新', 'success')
  } catch (error) {
    showMessage('更新菜单失败: ' + error, 'error')
  }
}

/**
 * 注册全局快捷键
 */
const registerShortcut = async () => {
  if (!newShortcut.value.trim()) {
    showMessage('请输入快捷键组合', 'warning')
    return
  }

  try {
    const result = await window.api.system.registerGlobalShortcut(newShortcut.value, shortcutAction.value)
    
    if (result.success) {
      shortcuts.value.push({
        key: newShortcut.value,
        description: getActionDescription(shortcutAction.value),
        action: shortcutAction.value
      })
      newShortcut.value = ''
      showMessage('快捷键注册成功！', 'success')
    } else {
      showMessage(result.message || '快捷键注册失败', 'error')
    }
  } catch (error) {
    showMessage('注册快捷键失败: ' + error, 'error')
  }
}

/**
 * 获取动作描述
 */
const getActionDescription = (action: string): string => {
  switch (action) {
    case 'show-hide-window': return '显示/隐藏窗口'
    case 'show-notification': return '发送测试通知'
    case 'custom-action': return '自定义动作'
    default: return '未知动作'
  }
}

/**
 * 移除快捷键
 */
const unregisterShortcut = async (key: string) => {
  try {
    await window.api.system.unregisterGlobalShortcut(key)
    shortcuts.value = shortcuts.value.filter(s => s.key !== key)
    showMessage('快捷键已移除', 'info')
  } catch (error) {
    showMessage('移除快捷键失败: ' + error, 'error')
  }
}

/**
 * 发送系统通知
 */
const sendNotification = async () => {
  if (!notification.title.trim()) {
    showMessage('请输入通知标题', 'warning')
    return
  }

  try {
    const notificationOptions = {
      title: notification.title,
      body: notification.body,
      silent: notification.silent,
      urgent: notification.urgent, // 添加紧急标志
      urgency: notification.urgent ? 'critical' : 'normal'
    }

    console.log('发送通知请求，参数:', notificationOptions)

    // 如果不是静音模式，播放前端声音作为备用
    if (!notification.silent) {
      playNotificationSound()
    }

    const result = await window.api.system.showNotification(notificationOptions)
    
    if (result.success) {
      // 添加到历史记录
      notificationHistory.value.unshift({
        time: new Date().toLocaleTimeString(),
        title: notification.title,
        body: notification.body
      })
      
      // 限制历史记录数量
      if (notificationHistory.value.length > 10) {
        notificationHistory.value = notificationHistory.value.slice(0, 10)
      }
      
      showMessage(
        `通知发送成功！${notification.urgent ? '（紧急通知）' : ''}`, 
        'success'
      )
    } else {
      showMessage(result.error || '通知发送失败', 'error')
    }
  } catch (error) {
    console.error('发送通知失败:', error)
    showMessage('发送通知失败: ' + error, 'error')
  }
}

/**
 * 播放通知声音（备用方案）
 */
const playNotificationSound = () => {
  try {
    // 方案1: 使用Web Audio API播放系统声音
    const audioContext = new (window.AudioContext || (window as any).webkitAudioContext)()
    
    // 创建一个简单的提示音
    const oscillator = audioContext.createOscillator()
    const gainNode = audioContext.createGain()
    
    oscillator.connect(gainNode)
    gainNode.connect(audioContext.destination)
    
    oscillator.frequency.setValueAtTime(800, audioContext.currentTime)
    oscillator.frequency.setValueAtTime(600, audioContext.currentTime + 0.1)
    
    gainNode.gain.setValueAtTime(0.3, audioContext.currentTime)
    gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.3)
    
    oscillator.start(audioContext.currentTime)
    oscillator.stop(audioContext.currentTime + 0.3)
    
    console.log('播放Web Audio提示音')
  } catch (error) {
    console.error('播放Web Audio失败:', error)
    
    // 方案2: 尝试使用HTML5 Audio（如果有音频文件）
    try {
      // 创建一个数据URL的简单提示音
      const audioData = 'data:audio/wav;base64,UklGRnoGAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQoGAACBhYqFbF1fdJivrJBhNjVgodDbq2EcBj+a2/LDciUFLIHO8tiJNwgZaLvt559NEAxQp+PwtmMcBjiR1/LMeSwFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBSuBzvLZiTYIG2m98OScTgwOUarm7blmGgU7k9n1unEiBC13yO/eizEIHWq+8+OWT'
      const audio = new Audio(audioData)
      audio.volume = 0.5
      audio.play()
      console.log('播放HTML5 Audio提示音')
    } catch (audioError) {
      console.error('播放HTML5 Audio失败:', audioError)
    }
  }
}

/**
 * 测试紧急通知
 */
const testUrgentNotification = async () => {
  try {
    const testOptions = {
      title: '🚨 紧急通知测试',
      body: '这是一个紧急通知，应该有声音提示！',
      silent: false,
      urgent: true,
      urgency: 'critical'
    }

    console.log('发送紧急测试通知，参数:', testOptions)

    // 先播放前端声音作为备用
    playNotificationSound()

    const result = await window.api.system.showNotification(testOptions)
    
    if (result.success) {
      notificationHistory.value.unshift({
        time: new Date().toLocaleTimeString(),
        title: testOptions.title,
        body: testOptions.body
      })
      
      // 限制历史记录数量
      if (notificationHistory.value.length > 10) {
        notificationHistory.value = notificationHistory.value.slice(0, 10)
      }
      
      showMessage('紧急通知测试成功！请检查是否有声音', 'success')
    } else {
      showMessage(result.error || '紧急通知发送失败', 'error')
    }
  } catch (error) {
    console.error('发送紧急测试通知失败:', error)
    showMessage('发送紧急测试通知失败: ' + error, 'error')
  }
}

/**
 * 设置自定义菜单
 */
const setCustomMenu = async () => {
  try {
    const menuTemplate = [
      {
        label: '文件',
        submenu: [
          { label: '新建文档', accelerator: 'Ctrl+N', action: 'new' },
          { label: '打开文件', accelerator: 'Ctrl+O', action: 'open' },
          { label: '保存', accelerator: 'Ctrl+S', action: 'save' },
          { label: '另存为', accelerator: 'Ctrl+Shift+S', action: 'saveAs' },
          { type: 'separator' },
          { label: '打印', accelerator: 'Ctrl+P', action: 'print' },
          { type: 'separator' },
          { label: '退出', accelerator: 'Ctrl+Q', role: 'quit' }
        ]
      },
      {
        label: '编辑',
        submenu: [
          { label: '撤销', accelerator: 'Ctrl+Z', role: 'undo' },
          { label: '重做', accelerator: 'Ctrl+Y', role: 'redo' },
          { type: 'separator' },
          { label: '剪切', accelerator: 'Ctrl+X', role: 'cut' },
          { label: '复制', accelerator: 'Ctrl+C', role: 'copy' },
          { label: '粘贴', accelerator: 'Ctrl+V', role: 'paste' },
          { label: '全选', accelerator: 'Ctrl+A', role: 'selectall' },
          { type: 'separator' },
          { label: '查找', accelerator: 'Ctrl+F', action: 'find' }
        ]
      },
      {
        label: '查看',
        submenu: [
          { label: '重新加载', accelerator: 'Ctrl+R', role: 'reload' },
          { label: '强制重新加载', accelerator: 'Ctrl+Shift+R', role: 'forceReload' },
          { label: '开发者工具', accelerator: 'F12', role: 'toggleDevTools' },
          { type: 'separator' },
          { label: '实际大小', accelerator: 'Ctrl+0', role: 'resetZoom' },
          { label: '放大', accelerator: 'Ctrl+Plus', role: 'zoomIn' },
          { label: '缩小', accelerator: 'Ctrl+-', role: 'zoomOut' },
          { type: 'separator' },
          { label: '切换全屏', accelerator: 'F11', role: 'togglefullscreen' }
        ]
      },
      {
        label: '窗口',
        submenu: [
          { label: '最小化', accelerator: 'Ctrl+M', role: 'minimize' },
          { label: '关闭', accelerator: 'Ctrl+W', role: 'close' },
          { type: 'separator' },
          { label: '新建窗口', accelerator: 'Ctrl+Shift+N', action: 'newWindow' },
          { label: '显示所有窗口', action: 'showAllWindows' }
        ]
      },
      {
        label: '工具',
        submenu: [
          { label: '设置', accelerator: 'Ctrl+,', action: 'preferences' },
          { label: '主题切换', accelerator: 'Ctrl+T', action: 'toggleTheme' },
          { label: '语言切换', accelerator: 'Ctrl+L', action: 'toggleLanguage' },
          { type: 'separator' },
          { label: '系统信息', action: 'systemInfo' },
          { label: '清除缓存', action: 'clearCache' }
        ]
      },
      {
        label: '帮助',
        submenu: [
          { label: '用户手册', action: 'userManual' },
          { label: '快捷键', action: 'shortcuts' },
          { label: '反馈问题', action: 'feedback' },
          { type: 'separator' },
          { label: '检查更新', action: 'checkUpdate' },
          { label: '关于 yuCloudEle', action: 'about' }
        ]
      }
    ]

    await window.api.system.setApplicationMenu(menuTemplate)
    menuStatus.isCustom = true
    showMessage('自定义菜单设置成功！菜单包含丰富的功能选项', 'success')
  } catch (error) {
    showMessage('设置菜单失败: ' + error, 'error')
  }
}

/**
 * 恢复默认菜单
 */
const resetDefaultMenu = async () => {
  try {
    await window.api.system.setApplicationMenu(null)
    menuStatus.isCustom = false
    showMessage('已恢复默认菜单', 'info')
  } catch (error) {
    showMessage('恢复菜单失败: ' + error, 'error')
  }
}

/**
 * 切换菜单栏显示
 */
const toggleMenuBar = async () => {
  try {
    const newState = !menuStatus.visible
    await window.api.system.setMenuBarVisibility(newState)
    menuStatus.visible = newState
    showMessage(`菜单栏已${newState ? '显示' : '隐藏'}`, 'info')
  } catch (error) {
    showMessage('切换菜单栏失败: ' + error, 'error')
  }
}

/**
 * 创建带菜单栏的演示窗口
 */
const createMenuWindow = async () => {
  try {
    const result = await window.api.window.createChild({
      title: '菜单栏演示窗口',
      width: 800,
      height: 600,
      frame: true, // 启用窗口边框以显示菜单栏
      autoHideMenuBar: false // 不自动隐藏菜单栏
    })
    
    if (result.success) {
      showMessage('带菜单栏的演示窗口已创建！您可以在新窗口中看到菜单栏效果', 'success')
    } else {
      showMessage(result.error || '创建菜单演示窗口失败', 'error')
    }
  } catch (error) {
    showMessage('创建菜单演示窗口失败: ' + error, 'error')
  }
}

/**
 * 注册自定义协议
 */
const registerProtocol = async () => {
  try {
    const result = await window.api.system.registerProtocol('yucloudele')
    
    if (result.success) {
      protocolStatus.registered = true
      showMessage('协议注册成功！现在可以通过 yucloudele:// 链接打开应用', 'success')
    }
  } catch (error) {
    showMessage('注册协议失败: ' + error, 'error')
  }
}

/**
 * 测试协议
 */
const testProtocol = () => {
  const testUrl = 'yucloudele://test?param=hello&from=demo'
  window.open(testUrl, '_blank')
  showMessage('已尝试打开协议链接', 'info')
}

/**
 * 切换开机自启动
 */
const toggleAutoLaunch = async () => {
  try {
    const newState = !autoLaunchStatus.enabled
    const result = await window.api.system.setAutoLaunch(newState)
    
    if (result.success) {
      autoLaunchStatus.enabled = newState
      autoLaunchStatus.path = newState ? 'Enabled' : 'Disabled'
      showMessage(`开机自启动已${newState ? '启用' : '禁用'}`, 'success')
    }
  } catch (error) {
    showMessage('设置自启动失败: ' + error, 'error')
  }
}

/**
 * 检查自启动状态
 */
const checkAutoLaunch = async () => {
  try {
    const result = await window.api.system.getAutoLaunchStatus()
    autoLaunchStatus.enabled = result.enabled
    autoLaunchStatus.path = result.executableWillLaunchAtLogin ? 'Enabled' : 'Disabled'
    showMessage('自启动状态已更新', 'info')
  } catch (error) {
    showMessage('检查自启动状态失败: ' + error, 'error')
  }
}

/**
 * 显示消息提示
 */
const showMessage = (text: string, type: 'success' | 'error' | 'warning' | 'info' = 'info') => {
  message.text = text
  message.type = type
  
  setTimeout(() => {
    message.text = ''
  }, 3000)
}

/**
 * 菜单动作处理器
 */
const handleMenuAction = (action: any) => {
  console.log('收到菜单动作:', action)
  
  switch (action.action) {
    case 'new':
      showMessage('📄 新建文档', 'info')
      break
    case 'open':
      showMessage('📂 打开文件', 'info')
      break
    case 'save':
      showMessage('💾 保存文档', 'info')
      break
    case 'saveAs':
      showMessage('💾 另存为', 'info')
      break
    case 'print':
      showMessage('🖨️ 打印文档', 'info')
      break
    case 'find':
      showMessage('🔍 查找内容', 'info')
      break
    case 'newWindow':
      showMessage('🪟 创建新窗口', 'info')
      break
    case 'showAllWindows':
      showMessage('🗂️ 显示所有窗口', 'info')
      break
    case 'preferences':
      router.push('/settings')
      showMessage('⚙️ 跳转到设置页面', 'success')
      break
    case 'toggleTheme':
      settings.toggleTheme()
      showMessage('🌙 主题已切换', 'success')
      break
    case 'toggleLanguage':
      settings.toggleLanguage()
      showMessage('🌐 语言已切换', 'success')
      break
    case 'systemInfo':
      showMessage(`💻 系统信息: ${navigator.platform} - ${navigator.userAgent.split(' ')[0]}`, 'info')
      break
    case 'clearCache':
      localStorage.clear()
      sessionStorage.clear()
      showMessage('🗑️ 缓存已清除', 'success')
      break
    case 'userManual':
      showMessage('📖 打开用户手册', 'info')
      break
    case 'shortcuts':
      showMessage('⌨️ 显示快捷键列表', 'info')
      break
    case 'feedback':
      showMessage('📝 反馈问题页面', 'info')
      break
    case 'checkUpdate':
      showMessage('🔄 检查更新...', 'info')
      break
    case 'about':
      showMessage('ℹ️ 关于 yuCloudEle - Electron 全功能演示应用 v1.0.0', 'info')
      break
    default:
      showMessage(`❓ 未知菜单动作: ${action.action}`, 'warning')
  }
}

// 生命周期
onMounted(async () => {
  showMessage('系统集成演示已就绪', 'success')
  
  // 监听菜单事件
  if (window.api && window.api.onMenuAction) {
    window.api.onMenuAction(handleMenuAction)
    console.log('菜单事件监听器已注册')
  } else {
    console.warn('菜单事件监听API不可用')
  }
  
  // 初始化状态检查
  try {
    // 检查托盘状态
    const trayResult = await window.api.system.getTrayStatus()
    trayStatus.created = trayResult.created
    
    // 检查自启动状态
    await checkAutoLaunch()
    
    // 预设并注册一些常用快捷键
    const presetShortcuts = [
      { key: 'Ctrl+Shift+H', action: 'show-hide-window', description: '显示/隐藏窗口' },
      { key: 'Ctrl+Shift+N', action: 'show-notification', description: '发送测试通知' }
    ]
    
    for (const preset of presetShortcuts) {
      try {
        const result = await window.api.system.registerGlobalShortcut(preset.key, preset.action)
        if (result.success) {
          shortcuts.value.push({
            key: preset.key,
            description: preset.description,
            action: preset.action
          })
          console.log(`预设快捷键注册成功: ${preset.key} -> ${preset.action}`)
        } else {
          console.warn(`预设快捷键注册失败: ${preset.key}`, result.message)
        }
      } catch (error) {
        console.error(`预设快捷键注册出错: ${preset.key}`, error)
      }
    }
    
    if (shortcuts.value.length > 0) {
      showMessage(`已注册 ${shortcuts.value.length} 个预设快捷键`, 'info')
    }
  } catch (error) {
    console.error('初始化系统集成状态失败:', error)
  }
})

onUnmounted(async () => {
  // 清理资源 - 注销所有快捷键
  for (const shortcut of shortcuts.value) {
    try {
      await window.api.system.unregisterGlobalShortcut(shortcut.key)
      console.log(`清理快捷键: ${shortcut.key}`)
    } catch (error) {
      console.error(`清理快捷键失败: ${shortcut.key}`, error)
    }
  }
  
  console.log('系统集成演示组件已卸载')
})
</script>

<style scoped>
.system-integration-page {
  min-height: 100vh;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  box-sizing: border-box;
}

.header {
  text-align: center;
  margin-bottom: 40px;
}

.header h2 {
  color: var(--text-primary, #2c3e50);
  margin: 0;
  font-size: 2.2em;
}

.subtitle {
  color: var(--text-secondary, #7f8c8d);
  margin: 5px 0 0 0;
  font-size: 1.1em;
}

.quick-menu-control {
  background: var(--bg-secondary);
  border: 2px solid var(--primary-color);
  border-radius: 12px;
  padding: 20px;
  text-align: center;
  margin-top: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.menu-status-text {
  margin: 10px 0 0 0;
  color: var(--text-secondary);
  font-size: 0.95rem;
  font-weight: 500;
}

.demo-sections {
  display: grid;
  gap: 30px;
}

.demo-section {
  background: var(--card-bg, #f8f9fa);
  border-radius: 12px;
  padding: 25px;
  border-left: 4px solid var(--primary-color, #3498db);
  box-shadow: var(--shadow-sm, 0 2px 10px rgba(0, 0, 0, 0.1));
  border: 1px solid var(--card-border, transparent);
}

.demo-section h3 {
  margin: 0 0 10px 0;
  color: var(--text-primary, #2c3e50);
  font-size: 1.3em;
}

.description {
  color: var(--text-secondary, #666);
  margin: 0 0 20px 0;
  font-size: 14px;
  line-height: 1.5;
}

.controls {
  display: flex;
  gap: 15px;
  align-items: center;
  flex-wrap: wrap;
  margin-bottom: 20px;
}

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  min-width: 100px;
}

.btn:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow, 0 4px 8px rgba(0, 0, 0, 0.2));
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.btn-primary {
  background: linear-gradient(45deg, var(--primary-color, #3498db), var(--primary-hover, #2980b9));
  color: var(--text-inverse, white);
  border: 1px solid var(--primary-color, transparent);
}

.btn-secondary {
  background: linear-gradient(45deg, var(--text-secondary, #95a5a6), #7f8c8d);
  color: var(--text-inverse, white);
  border: 1px solid var(--text-secondary, transparent);
}

.btn-success {
  background: linear-gradient(45deg, var(--success-color, #2ecc71), var(--success-hover, #27ae60));
  color: var(--text-inverse, white);
  border: 1px solid var(--success-color, transparent);
}

.btn-danger {
  background: linear-gradient(45deg, var(--error-color, #e74c3c), var(--error-hover, #c0392b));
  color: var(--text-inverse, white);
  border: 1px solid var(--error-color, transparent);
}

.btn-warning {
  background: linear-gradient(45deg, var(--warning-color, #f39c12), #e67e22);
  color: var(--text-inverse, white);
  border: 1px solid var(--warning-color, transparent);
}

.btn-lg {
  padding: 15px 30px;
  font-size: 18px;
  font-weight: 600;
  min-width: 200px;
  border-radius: 8px;
}

.btn-info {
  background: linear-gradient(45deg, var(--info-color, #3498db), #2980b9);
  color: var(--text-inverse, white);
  border: 1px solid var(--info-color, transparent);
}

.btn-sm {
  padding: 5px 10px;
  font-size: 12px;
  min-width: 60px;
}

.input, .textarea {
  padding: 10px 15px;
  border: 2px solid var(--input-border, #bdc3c7);
  border-radius: 6px;
  font-size: 14px;
  background: var(--input-bg, white);
  color: var(--text-primary, #333);
}

.input {
  min-width: 200px;
}

.textarea {
  min-width: 300px;
  min-height: 80px;
  resize: vertical;
  font-family: inherit;
}

.input:focus, .textarea:focus {
  outline: none;
  border-color: var(--primary-color, #3498db);
  box-shadow: var(--input-focus-shadow, 0 0 0 0.2rem rgba(52, 152, 219, 0.25));
}

.status-info {
  background: var(--success-light, #e8f5e8);
  border: 1px solid var(--success-color, #4caf50);
  border-radius: 6px;
  padding: 15px;
  color: var(--success-color, #2e7d32);
  font-size: 14px;
}

.status-info p {
  margin: 5px 0;
}

.shortcut-item {
  display: flex;
  gap: 10px;
  align-items: center;
  width: 100%;
}

.action-select {
  padding: 10px;
  border: 2px solid var(--border-color, #bdc3c7);
  border-radius: 6px;
  background: var(--input-bg, white);
  color: var(--text-primary, #333);
  font-size: 14px;
  min-width: 150px;
}

.action-select:focus {
  outline: none;
  border-color: var(--primary-color, #3498db);
  box-shadow: var(--input-focus-shadow, 0 0 0 0.2rem rgba(52, 152, 219, 0.25));
}

.shortcut-list {
  margin-top: 20px;
}

.shortcut-list h4 {
  color: var(--text-primary, #333);
  margin: 0 0 15px 0;
}

.empty-state {
  color: var(--text-muted, #999);
  font-style: italic;
  text-align: center;
  padding: 20px;
}

.shortcut-card {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 12px;
  background: var(--bg-secondary, #f0f0f0);
  border-radius: 6px;
  margin-bottom: 10px;
  border: 1px solid var(--border-color, transparent);
}

.shortcut-key {
  background: var(--text-primary, #333);
  color: var(--text-inverse, white);
  padding: 4px 8px;
  border-radius: 4px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
  min-width: 120px;
  text-align: center;
}

.shortcut-desc {
  flex: 1;
  color: var(--text-primary, #333);
}

.shortcut-action {
  background: var(--primary-light, rgba(52, 152, 219, 0.1));
  color: var(--primary-color, #3498db);
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 11px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  border: 1px solid var(--primary-color, #3498db);
}

.notification-form {
  display: flex;
  flex-direction: column;
  gap: 15px;
  width: 100%;
  max-width: 500px;
}

.notification-controls {
  display: flex;
  gap: 10px;
  align-items: center;
}

.notification-controls .btn {
  flex: 1;
  min-width: 100px;
  font-size: 14px;
}

.notification-options {
  display: flex;
  gap: 20px;
}

.checkbox-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--text-primary, #333);
  cursor: pointer;
}

.checkbox-item input[type="checkbox"] {
  margin: 0;
}

.notification-history {
  margin-top: 20px;
}

.notification-history h4 {
  color: var(--text-primary, #333);
  margin: 0 0 15px 0;
}

.history-list {
  max-height: 300px;
  overflow-y: auto;
}

.history-item {
  display: flex;
  gap: 15px;
  padding: 12px;
  background: var(--bg-secondary, #f9f9f9);
  border-radius: 6px;
  margin-bottom: 10px;
  border: 1px solid var(--border-color, #e0e0e0);
}

.history-time {
  color: var(--text-muted, #666);
  font-size: 12px;
  min-width: 80px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
}

.history-content {
  flex: 1;
}

.history-content strong {
  color: var(--text-primary, #333);
  display: block;
  margin-bottom: 4px;
}

.history-content p {
  color: var(--text-secondary, #666);
  margin: 0;
  font-size: 14px;
}

.menu-info, .protocol-info, .autolaunch-info {
  background: var(--bg-tertiary, #f5f5f5);
  border-radius: 6px;
  padding: 15px;
  margin-top: 15px;
  border: 1px solid var(--border-color, #ddd);
}

.menu-info p, .protocol-info p, .autolaunch-info p {
  margin: 5px 0;
  color: var(--text-primary, #333);
}

.menu-notice {
  background: var(--primary-light, rgba(52, 152, 219, 0.1));
  border: 1px solid var(--primary-color, #3498db);
  border-radius: 6px;
  padding: 12px;
  margin-top: 10px;
}

.menu-notice p {
  margin: 4px 0;
  font-size: 0.9rem;
  line-height: 1.4;
  color: var(--text-primary, #333);
}

.menu-notice strong {
  color: var(--primary-color, #3498db);
}

.protocol-info code {
  background: var(--text-primary, #333);
  color: var(--text-inverse, white);
  padding: 2px 6px;
  border-radius: 4px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
}

/* 消息提示样式 */
.message {
  position: fixed;
  top: 20px;
  right: 20px;
  padding: 15px 20px;
  border-radius: 8px;
  color: var(--text-inverse, white);
  font-weight: 600;
  z-index: 1000;
  animation: slideIn 0.3s ease;
  max-width: 400px;
  box-shadow: var(--shadow, 0 4px 12px rgba(0, 0, 0, 0.15));
}

.message.success {
  background: var(--success-color, #28a745);
}

.message.error {
  background: var(--error-color, #dc3545);
}

.message.warning {
  background: var(--warning-color, #ffc107);
  color: var(--text-primary, #333);
}

.message.info {
  background: var(--info-color, #17a2b8);
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .system-integration-page {
    padding: 15px;
  }
  
  .controls {
    flex-direction: column;
    align-items: stretch;
  }
  
  .btn {
    width: 100%;
  }
  
  .input, .textarea {
    min-width: 100%;
  }
  
  .shortcut-item {
    flex-direction: column;
  }
  
  .notification-form {
    max-width: 100%;
  }
}
</style>
